//
//  WXPhotoCollectionView.swift
//  weibo
//
//  Created by 王旭 on 16/4/22.
//  Copyright © 2016年 王旭. All rights reserved.
//

import UIKit

//放在里面报错
let Photomargin : CGFloat = 5
let PhotoWH : CGFloat = {
    let IntWH : Int = Int((SCREEN_W - 2 * HomeCellMargin - 2 * Photomargin) / 3)
    let FloatWH : CGFloat = CGFloat(IntWH)
    return FloatWH
}()
class WXPhotoCollectionView: UICollectionView {

    
    //重用标识符
    var reuseIdetifier = "Home_photo_cell"
    
    //元组
    var dataInfo: (pic_urls: [WXHomePhotoModel], size: CGSize)?{
        didSet{
            if dataInfo?.pic_urls.count == 1 {
                let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = dataInfo?.size ?? CGSizeZero
            }else{
                let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = CGSize(width: PhotoWH, height: PhotoWH)
            }
            
            //更新约束
            self.snp_updateConstraints(closure: { (make) -> Void in
                make.size.equalTo(dataInfo?.size ?? CGSizeZero)
            })
        }
    }
    
    //配图
//    var pic_urls: [WXHomePhotoModel]?{
//        didSet{
//            photoCountLabel.text = "\(pic_urls?.count ?? 0)"
//        }
//    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //布局界面
    func setupUI() {
        
    backgroundColor = UIColor(white: 180/255, alpha: 1)
        
        //注册cell
        registerClass(WXHomePhotoCell.self, forCellWithReuseIdentifier: reuseIdetifier)
        
        //布局collectionView的cell
        let layout = collectionViewLayout as? UICollectionViewFlowLayout
        layout?.itemSize = CGSize(width: PhotoWH, height: PhotoWH)
        //cell间间距
        layout?.minimumInteritemSpacing = Photomargin
        layout?.minimumLineSpacing = Photomargin
        
        //设置代理
        self.dataSource = self
        self.delegate = self
        //添加控件
        addSubview(photoCountLabel)
        
        //约束
        photoCountLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
    }
    
    private lazy var photoCountLabel : UILabel = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 35)

}

//数据源方法
extension WXPhotoCollectionView:UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataInfo?.pic_urls.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdetifier, forIndexPath: indexPath) as! WXHomePhotoCell
        
        cell.backgroundColor = UIColor(white: 180/255, alpha: 1)
        
        cell.imageInfo = dataInfo!.pic_urls[indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        let photoBrowser = SDPhotoBrowser()
//        photoBrowser.delegate = self
//        // 设置当前点击的索引
//        photoBrowser.currentImageIndex = indexPath.item
//        // 设置总张数
//        photoBrowser.imageCount = dataInfo!.pic_urls.count
//        // 设置当前点击控件的容器视图
//        photoBrowser.sourceImagesContainerView = self
//        
//        photoBrowser.show()
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        //当前索引
        photoBrowser.currentImageIndex = indexPath.item
        //总张数
        photoBrowser.imageCount = dataInfo!.pic_urls.count
        //控件容器视图
        photoBrowser.sourceImagesContainerView = self
        
        photoBrowser.show()
    }
}

extension WXPhotoCollectionView:SDPhotoBrowserDelegate {
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        //1.取到cell
        let cell = self.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0))! as! WXHomePhotoCell
        //2.取到Image
        return cell.iconImageView.image
    }
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        //urlStr
        let urlStr = dataInfo!.pic_urls[index].thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        print(urlStr)
        return NSURL(string: urlStr)
    }
}

//自定义collectionViewCell
class WXHomePhotoCell : UICollectionViewCell {
    
    //图片数据
    var imageInfo: WXHomePhotoModel?{
        didSet{
            //设置图片
            iconImageView.sd_setImageWithURL(NSURL(string: imageInfo?.thumbnail_pic ?? ""), placeholderImage: UIImage(named: "timeline_image_placeholder"))
            
            //gif
            iconImageView_gif.hidden = !(imageInfo?.thumbnail_pic ?? "" ).hasSuffix(".gif")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        //添加控件
        addSubview(iconImageView)
        addSubview(iconImageView_gif)
        //约束
        iconImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        
        iconImageView_gif.snp_makeConstraints { (make) -> Void in
            make.bottom.right.equalTo(iconImageView)
        }
    }
    
    //懒加载
    
    //图片
    private lazy var iconImageView :UIImageView = {
      let iconImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
    //内容模式
        iconImageView.contentMode = .ScaleAspectFill
    //切掉多余的部分
        iconImageView.layer.masksToBounds = true
    return iconImageView
    }()
    
    //gif
    private lazy var iconImageView_gif :UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}
